var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var logger = require('../../util/logs');

exports.setup = function (User, config) {
    passport.use(new LocalStrategy({
            usernameField: 'phone',
            passwordField: 'password' // this is the virtual field on the model
        },
        function (phone, password, done) {
            User.findOne({
                phone: phone.toLowerCase()
            }, function (err, user) {
                if (err) return done(err);
                if (!user) {
                    logger.error('登录用户名错误', {'username': phone});
                    return done(null, false, {error_msg: '用户名或密码错误.'});
                }
                if (!user.authenticate(password)) {
                    logger.error('登录密码错误', {'username': phone});
                    return done(null, false, {error_msg: '用户名或密码错误.'});
                }

                if (user.status === 2) {
                    logger.error('被阻止登录', {'username': phone});
                    return done(null, false, {error_msg: '用户被阻止登录.'});
                }
                if (user.status === 0) {
                    logger.error('未验证用户登录', {'username': phone});
                    return done(null, false, {error_msg: '用户未验证.'});
                }
                console.log('进入password中间件');
                return done(null, user);
            });
        }
    ));
};